<template>
  <div class="date-range-picker">
    <!-- 头部 - 显示已选日期 -->
    <div class="header">
      <div class="selected-dates">
        <div class="date-row">
          <span class="date-label">起始日期:</span>
          <span class="date-value">{{ selectedStartDate || '未选择' }}</span>
        </div>
        <div class="date-row">
          <span class="date-label">结束日期:</span>
          <span class="date-value">{{ selectedEndDate || '未选择' }}</span>
        </div>
      </div>
    </div>
    <!-- 控制栏 - 年月切换 -->
    <div class="controls">
      <button @click="prevYear" class="control-btn" title="上一年">
        <el-icon><DArrowLeft /></el-icon>
      </button>
      <button @click="prevMonth" class="control-btn" title="上一月">
        <el-icon><ArrowLeft /></el-icon>
      </button>
      <span class="current-month">{{ displayYear }}年{{ displayMonth }}月</span>
      <button @click="nextMonth" class="control-btn" title="下一月">
        <el-icon><ArrowRight /></el-icon>
      </button>
      <button @click="nextYear" class="control-btn" title="下一年">
        <el-icon><DArrowRight /></el-icon>
      </button>
    </div>

    <!-- 星期标题 -->
    <div class="weekdays">
      <div v-for="day in weekdays" :key="day" class="weekday">{{ day }}</div>
    </div>

    <!-- 日期网格 -->
    <div class="days-grid">
      <div 
        v-for="(day, index) in days" 
        :key="index"
        :class="[
          'day',
          {
            'other-month': !day.isCurrentMonth,
            'selected-start': isSelectedStart(day.date),
            'selected-end': isSelectedEnd(day.date),
            'in-range': isInRange(day.date),
            'today': isToday(day.date),
            'disabled': isDisabled(day.date),
            'past-date': isPastDate(day.date)
          }
        ]"
        @click="selectDate(day.date)"
      >
        {{ day.day }}
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div class="footer">
      <div class="footer-left">
        <button @click="clearSelection" class="action-btn clear-btn">清空</button>
      </div>
      <div class="footer-right">
        <button @click="cancelSelection" class="action-btn cancel-btn">退出</button>
        <button @click="confirmSelection" class="action-btn confirm-btn">确定</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { ElIcon } from 'element-plus';
import { ArrowLeft, ArrowRight, DArrowLeft, DArrowRight } from '@element-plus/icons-vue';
/**
 * 组件属性定义
 * minDate: 可选的最小日期
 * maxDate: 可选的最大日期
 */
const props = defineProps({
  minDate: {
    type: Date,
    default: null
  },
  maxDate: {
    type: Date,
    default: null
  }
});

/**
 * 组件事件定义
 * update: 当日期选择变化时触发
 * cancel: 当点击退出按钮时触发
 */
const emit = defineEmits(['update', 'cancel']);

// 当前日期实例
const currentDate = new Date();
// 显示的年月
const displayYear = ref(currentDate.getFullYear());
const displayMonth = ref(currentDate.getMonth() + 1);
// 选择的起始和结束日期
const selectedStartDate = ref('');
const selectedEndDate = ref('');
// 星期标题
const weekdays = ['日', '一', '二', '三', '四', '五', '六'];

/**
 * 计算属性：生成当前显示月份的日期数组
 * 包括上个月的部分日期和下个月的部分日期
 */
const days = computed(() => {
  // 当月第一天
  const firstDayOfMonth = new Date(displayYear.value, displayMonth.value - 1, 1);
  // 当月最后一天
  const lastDayOfMonth = new Date(displayYear.value, displayMonth.value, 0);
  // 当月天数
  const daysInMonth = lastDayOfMonth.getDate();
  
  // 当月第一天是星期几
  const firstDayOfWeek = firstDayOfMonth.getDay();
  // 需要显示的上个月天数
  const daysFromPrevMonth = firstDayOfWeek;
  
  // 当月最后一天是星期几
  const lastDayOfWeek = lastDayOfMonth.getDay();
  // 需要显示的下个月天数
  const daysFromNextMonth = 6 - lastDayOfWeek;
  
  const daysArray = [];
  
  // 添加上个月的日期
  const prevMonthLastDay = new Date(displayYear.value, displayMonth.value - 1, 0).getDate();
  for (let i = daysFromPrevMonth - 1; i >= 0; i--) {
    const day = prevMonthLastDay - i;
    daysArray.push({
      day,
      date: new Date(displayYear.value, displayMonth.value - 2, day),
      isCurrentMonth: false
    });
  }
  
  // 添加当月的日期
  for (let i = 1; i <= daysInMonth; i++) {
    daysArray.push({
      day: i,
      date: new Date(displayYear.value, displayMonth.value - 1, i),
      isCurrentMonth: true
    });
  }
  
  // 添加下个月的日期
  for (let i = 1; i <= daysFromNextMonth; i++) {
    daysArray.push({
      day: i,
      date: new Date(displayYear.value, displayMonth.value, i),
      isCurrentMonth: false
    });
  }
  
  return daysArray;
});

/**
 * 检查日期是否为过去的日期
 */
const isPastDate = (date) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const checkDate = new Date(date);
  checkDate.setHours(0, 0, 0, 0);
  return checkDate < today;
};

/**
 * 检查日期是否被选为起始日期
 */
const isSelectedStart = (date) => {
  return selectedStartDate.value === formatDate(date);
};

/**
 * 检查日期是否被选为结束日期
 */
const isSelectedEnd = (date) => {
  return selectedEndDate.value === formatDate(date);
};

/**
 * 检查日期是否在选择的范围内
 */
const isInRange = (date) => {
  if (!selectedStartDate.value || !selectedEndDate.value) return false;
  
  const dateStr = formatDate(date);
  const start = selectedStartDate.value;
  const end = selectedEndDate.value;
  
  return dateStr > start && dateStr < end;
};

/**
 * 检查日期是否是今天
 */
const isToday = (date) => {
  return formatDate(date) === formatDate(new Date());
};

/**
 * 检查日期是否被禁用
 */
const isDisabled = (date) => {
  const dateStr = formatDate(date);
  
  // 检查是否小于最小日期
  if (props.minDate && dateStr < formatDate(props.minDate)) return true;
  // 检查是否大于最大日期
  if (props.maxDate && dateStr > formatDate(props.maxDate)) return true;
  // 检查是否是过去的日期
  if (isPastDate(date)) return true;
  
  return false;
};

/**
 * 格式化日期为YYYY-MM-DD格式
 */
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  return `${year}-${month}-${day}`;
};

/**
 * 选择日期
 */
const selectDate = (date) => {
  if (isDisabled(date)) return;
  
  const dateStr = formatDate(date);
  
  // 如果没有选择起始日期，或者已经选择了起始和结束日期，则重新选择
  if (!selectedStartDate.value || (selectedStartDate.value && selectedEndDate.value)) {
    selectedStartDate.value = dateStr;
    selectedEndDate.value = '';
  } 
  // 如果选择了起始日期但未选择结束日期
  else if (selectedStartDate.value && !selectedEndDate.value) {
    // 如果选择的日期在起始日期之前，则交换
    if (dateStr < selectedStartDate.value) {
      selectedEndDate.value = selectedStartDate.value;
      selectedStartDate.value = dateStr;
    } else {
      selectedEndDate.value = dateStr;
    }
  }
};

/**
 * 切换到上个月
 */
const prevMonth = () => {
  if (displayMonth.value === 1) {
    displayMonth.value = 12;
    displayYear.value--;
  } else {
    displayMonth.value--;
  }
};

/**
 * 切换到下个月
 */
const nextMonth = () => {
  if (displayMonth.value === 12) {
    displayMonth.value = 1;
    displayYear.value++;
  } else {
    displayMonth.value++;
  }
};

/**
 * 切换到上一年
 */
const prevYear = () => {
  displayYear.value--;
};

/**
 * 切换到下一年
 */
const nextYear = () => {
  displayYear.value++;
};


/**
 * 清空选择
 */
const clearSelection = () => {
  selectedStartDate.value = '';
  selectedEndDate.value = '';
};

/**
 * 确认选择
 */
const confirmSelection = () => {
  emit('update', {
    startDate: selectedStartDate.value,
    endDate: selectedEndDate.value
  });
};

/**
 * 取消选择/退出
 */
const cancelSelection = () => {
  emit('cancel', false);
};

// 监听日期选择变化，确保起始日期不大于结束日期
watch([selectedStartDate, selectedEndDate], () => {
  if (selectedStartDate.value && selectedEndDate.value) {
    if (selectedStartDate.value > selectedEndDate.value) {
      const temp = selectedStartDate.value;
      selectedStartDate.value = selectedEndDate.value;
      selectedEndDate.value = temp;
    }
  }
});
</script>

<style lang="scss" scoped>
// 导入SASS颜色模块
@use "sass:color";

// 颜色变量 - 参考task.vue的设计风格
$primary-color: #4c6fb4;
$primary-hover: #3a5a9c;
$danger-color: #eb5757;
$success-color: #67c23a;
$warning-color: #e6a23c;
$bg-light: #f5f7fa;
$bg-lighter: #f2f3f5;
$border-color: #dcdfe6;
$text-primary: #303133;
$text-secondary: #606266;
$text-tertiary: #909399;

// 日历容器 - 自适应外部大小
.date-range-picker {
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
  width: 100%;
  height: 100%;
  padding: 16px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

// 头部样式
.header {
  flex-shrink: 0;
  .selected-dates {
    padding: 12px;
    background-color: $bg-light;
    border-radius: 6px;
    border-left: 3px solid $primary-color;
    
    .date-row {
      display: flex;
      align-items: center;
      margin: 4px 0;
      font-size: 14px;
    }
    
    .date-label {
      font-weight: 500;
      color: $text-secondary;
      min-width: 70px;
    }
    
    .date-value {
      color: $primary-color;
      font-weight: 600;
      flex: 1;
      text-align: left;
    }
  }
}

// 控制栏样式
.controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
  padding: 8px 0;
  border-bottom: 1px solid $border-color;
  
  .control-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    background: none;
    border: 1px solid $border-color;
    border-radius: 4px;
    padding: 4px 10px;
    cursor: pointer;
    transition: all 0.3s ease;
    color: $text-secondary;
    font-size: 14px;
    min-width: 32px;
    height: 32px;
    
    &:hover {
      color: white;
      border-color: $primary-color;
      background-color: color.adjust($primary-color, $alpha: 0.05);
    }
    
    &:active {
      transform: translateY(1px);
    }
  }
  
  .current-month {
    font-weight: 600;
    font-size: 16px;
    color: $text-primary;
  }
}

// 星期标题样式
.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  margin-bottom: 8px;
  
  .weekday {
    font-weight: 500;
    color: $text-tertiary;
    font-size: 12px;
    padding: 6px 0;
    text-transform: uppercase;
  }
}

// 日期网格样式 - 自适应高度
.days-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 4px;
  flex: 1;
  overflow: hidden;
  .day {
    min-height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 5px;
    cursor: pointer;
    font-size: 13px;
    transition: all 0.2s ease;
    position: relative;
    
    &:hover:not(.disabled) {
      background-color: $bg-lighter;
      transform: translateY(-1px);
    }
    
    &.other-month {
      color: #dcdfe6;
    }
    
    &.selected-start {
      background-color: $primary-color;
      color: white !important;
      font-weight: 500;
      border-radius: 5px;
      
      &:hover {
        background-color: $primary-hover;
      }
    }
    
    &.selected-end {
      background-color: $primary-color;
      color: white !important;
      font-weight: 500;
      border-radius: 5px;
      
      &:hover {
        background-color: $primary-hover;
      }
    }

    &.in-range {
      background-color: color.adjust($primary-color, $alpha: 0.1);
      color: white !important;
      border-radius: 5px;
    }
    
    &.today {
      position: relative;
      font-weight: 600;
      color: $primary-color;
      
      &:after {
        content: '';
        position: absolute;
        bottom: 2px;
        left: 50%;
        transform: translateX(-50%);
        width: 3px;
        height: 3px;
        background-color: $primary-color;
        border-radius: 50%;
      }
      
      &.selected-start,
      &.selected-end {
        &:after {
          background-color: white;
        }
      }
    }
    
    &.disabled,
    &.past-date {
      color: #c0c4cc;
      cursor: not-allowed;
      background-color: $bg-lighter;
      opacity: 0.7;
      
      &:hover {
        transform: none;
        background-color: $bg-lighter;
      }
    }
    
    &.past-date {
      text-decoration: line-through;
    }
  }
}

// 底部按钮区域 - 重新设计为左右布局
.footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
  padding-top: 12px;
  border-top: 1px solid $border-color;
  flex-shrink: 0;
  
  .footer-left,
  .footer-right {
    display: flex;
    gap: 10px;
  }
  
  .action-btn {
    padding: 6px 16px;
    border: 1px solid $border-color;
    border-radius: 4px;
    background-color: white;
    cursor: pointer;
    transition: all 0.3s ease;
    font-weight: 500;
    font-size: 13px;
    min-width: 60px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    }
    
    &:active {
      transform: translateY(0);
    }
    
    &.today-btn {
      color: $primary-color;
      border-color: $primary-color;
      
      &:hover {
        background-color: $primary-color;
        color: white;
      }
    }
    
    &.clear-btn {
      color: $warning-color;
      border-color: $warning-color;
      
      &:hover {
        background-color: $warning-color;
        color: white;
      }
    }
    
    &.confirm-btn {
      border-color: $success-color;
      color: $success-color;
      
      &:hover {
        background-color: $success-color;
        color: white;
      }
    }
    
    &.cancel-btn {
      border-color: $danger-color;
      color: $danger-color;
      
      &:hover {
        background-color: $danger-color;
        color: white;
      }
    }
  }
}

// 响应式设计
@media (max-width: 480px) {
  .date-range-picker {
    padding: 12px;
    gap: 12px;
  }
  
  .footer {
    flex-direction: column-reverse;
    gap: 10px;
    
    .footer-left,
    .footer-right {
      width: 100%;
      justify-content: space-between;
    }
    
    .action-btn {
      flex: 1;
      margin: 0 2px;
    }
  }
  
  .days-grid {
    gap: 3px;
    
    .day {
      min-height: 28px;
      font-size: 12px;
    }
  }
  
  .control-btn {
    min-width: 28px;
    height: 28px;
    padding: 4px 8px;
  }
  
  .current-month {
    font-size: 14px;
  }
}

// 适配对话框容器大小
:deep(.el-dialog__body) {
  padding: 0 !important;
  overflow: hidden;
}

// 当作为独立组件使用时的最小尺寸
.date-range-picker {
  min-width: 280px;
  min-height: 340px;
}
</style>